$(document).ready(function (){
	
	var NewGrade;
	$(".testrecitem").click(function() {
		var cell = $(this);
		var id = $(this).attr("id");
		GetTestRecDetails(id);	
		$( "#TestRecordDialog" ).dialog({
			width: 500,
			  modal: true,
			  buttons: {
				"Submit Changes": function() {
					
					UpdateGrade(id, $("#PointsGiven").val());
					cell.html(NewGrade);
					$( this ).dialog( "close" );
					
				},
				Cancel: function() {
				  $( this ).dialog( "close" );
				}
			  }
			
			});
	});
	
	
	$("#PointsGiven").change(function (){
		NewGrade = CalculateGrade();
	});
	
});

function GetTestRecDetails(TestRecID)
{
	LoadingStart();
	$.ajax({
			 url: "webservices.php",
			 type: "POST",
			 data: { Func: 'Get_student_test_details', TestRecordID: TestRecID },
			 dataType: 'json',
			 success: function (data) {
				console.log(data);
				
				$("#TestNameVal").html(data[0].TestName);
				$("#StudentNameVal").html(data[0].FullName);
				$("#DatetimeVal").html(data[0].TakenDate);
				
				var MaxPoints = data[0].MaxPoints;
				
				$("#PointsGiven").html("");
				
				for(var counter  = 1; counter <= MaxPoints; counter++)
				{
					$("#PointsGiven").append('<option value="' + counter + '">' + counter + '</option>');
				}
				
				$("#PointsGiven").val(data[0].PointsGiven);
				$("#GradeVal").html(data[0].Grade + " %");
				
				$("#MaxPoints").html(MaxPoints);
				
				LoadingEnd();
			 },
			 error: function (e)
			 {
				console.log(e);
			 }
	});

}

function CalculateGrade()
{
	var NewPoints = parseInt($("#PointsGiven").val());
	var MaxPoints = parseInt($("#MaxPoints").html());
	var NewGrade = Number(((NewPoints / MaxPoints) * 100).toFixed(2)); 
	
	$("#GradeVal").html(NewGrade + ' %');
	
	return NewGrade;
}

function LoadingStart()
{
	$("#TestRecDetail").css("visibility", "hidden");
	$("#LoaderBar").css("display", "inline-block");
	$(".ui-dialog-buttonset").css("visibility", "hidden");
}

function LoadingEnd()
{
	$("#TestRecDetail").css("visibility", "visible");
	$("#LoaderBar").css("display", "none");
	$(".ui-dialog-buttonset").css("visibility", "visible");
}

function UpdateGrade(TestRecID, Points)
{
	
	$.ajax({
			 url: "webservices.php",
			 type: "POST",
			 data: { Func: 'Update_test_point', TestRecordID: TestRecID, NewPoints: Points  },
			 dataType: 'json',
			 success: function (data) {
				
				 console.log("success");
				 //$("#table_id").dataTable().fnDraw();
			 },
			 error: function (e)
			 {
				console.log(e);
			 }
	});

}